package com.yaopaikeji.ExceptionHandler;

import com.yaopaikeji.constants.RestResult;
import com.yaopaikeji.constants.ResultsEnum;
import com.yaopaikeji.exception.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BaseException.class)
    public RestResult<String> handlerException(BaseException ex) {

        RestResult<String> restResult;

        if (ex instanceof InsertException) {
            restResult = new RestResult<>(ResultsEnum.DB_ERROR, ex.getMessage());
        } else if (ex instanceof UpdateException) {
            restResult = new RestResult<>(ResultsEnum.DB_ERROR, ex.getMessage());
        } else if (ex instanceof SelectException) {
            restResult = new RestResult<>(ResultsEnum.DB_ERROR, ex.getMessage());
        } else if (ex instanceof InvalidNullException) {
            restResult = new RestResult<>(ResultsEnum.DB_ERROR, ex.getMessage());
        } else if (ex instanceof DeleteException) {
            restResult = new RestResult<>(ResultsEnum.DB_ERROR, ex.getMessage());
        } else if(ex instanceof AuthenticationException) {
            restResult = new RestResult<>(ResultsEnum.AUTHENTICATION_FAIL, ex.getMessage());
        } else if(ex instanceof LoginFailException) {
            restResult = new RestResult<>(ResultsEnum.LOGIN_FAIL,ex.getMessage());
        } else {
            restResult = new RestResult<>(ResultsEnum.SYS_ERROR,"");
        }

        logger.error("error:", ex);

        return restResult;
    }

    @ExceptionHandler(Exception.class)
    public RestResult<String> systemErrorHandler(Exception ex) {

        logger.error("error:", ex);
        return new RestResult<>(ResultsEnum.UNKNOWN_ERROR,"");
    }
}
